<?php

namespace frontend\controllers;


use backend\models\Goods;
use EasyWeChat\Foundation\Application;
use frontend\models\BindForm;
use frontend\models\Member;
use frontend\models\Order;
use Overtrue\Socialite\User;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\Controller;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\News;
use frontend\models\LoginForm;
use frontend\models\Cart;

class WechatController extends Controller
{
    public $enableCsrfValidation = false;
    public $layout = 'main';

    public function behaviors()
    {
        return [
            'acf'=>[
                'class'=>AccessControl::className(),
                'only'=>['user','orders'],
                'rules'=>[
                    [
                        'allow'=>true,
                        'actions'=>['user','orders',''],
                        'roles'=>['@'],

                    ],
                ],
                //当访问用户，没有权限是，不符合要求时，该匿名函数将被调用
                'denyCallback'=>function($rule,$action){
                    //保存当前访问的路由
                    \Yii::$app->session->set('back',$this->action->uniqueId);
                    //获取当前用户的openid
                    if(!\Yii::$app->session->has('openid')) {
                        return $this->redirect(['wechat/get-openid']);
                    }
                    //跳转到绑定账号页面
                    return $this->redirect(['wechat/bind-acount']);
                },
            ],

        ];
    }

    public function actionIndex(){

        $app = new Application(\Yii::$app->params['wechat']);

        $server = $app->server;

        $server->setMessageHandler(function ($message) {
            switch ($message->MsgType) {
                case 'event':
                    if($message->Event == 'CLICK'){
                        //美女排行榜
                        if($message->EventKey=='V1001_Beauty_Ranking'){
                            $articles = [
                                //['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2011/12/20111202142224263950.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2013/04/20130423090055953093.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2011/11/20111114224745296423.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2014/12/20141225170742418902.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2013/05/20130501145311588608.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2014/12/20141225171119990603.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2014/12/20141225144832960024.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2014/10/20141027222213817061.jpg','Url'=>''],
                                ['title'=>'','Description'=>'','PicUrl'=>'http://mei.hercity.com/data/upfiles/thumb/2011/11/20111101161958723510.jpg','Url'=>''],
                            ];
                            $results = [];
                            foreach ($articles as $article){
                                $news = new News([
                                    'title'       => $article['title'],
                                    'description' => $article['Description'],
                                    'url'         => $article['Url'],
                                    'image'       => $article['PicUrl'],
                                ]);
                                $results[] = $news;
                            }
                            return $results;
                        }elseif($message->EventKey=='V1001_HELP'){
                            return 'help';
                        }elseif($message->EventKey=='V1001_Hot_Goods'){
                            return $this->actionHotGoods();
                        }
                    }

                    $data = serialize($message->EventKey);

                    return '收到事件消息'.$data;
                    break;
                case 'text':
                    if($message->Content == '帮助'){
                        return '帮助信息';
                    }elseif ($message->Content =='解除绑定' ){
                        if(!\Yii::$app->user->isGuest) {
                            $this->actionUnbound();
                        }
                        return '解除绑定成功';
                    }
                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        $response = $server->serve();
        // 将响应输出
        $response->send(); // Laravel 里请使用：return $response;


    }
    public function actionGetMenu(){

        //使用配置初始化项目
        $app = new Application(\Yii::$app->params['wechat']);
        //实例化菜单模型
        $menu = $app->menu;
        //查询菜单
        $menus = $menu->all();

        var_dump($menus);
    }
    public function actionSetMenu(){
        //使用配置初始化项目
        $app = new Application(\Yii::$app->params['wechat']);
        //实例化菜单模型
        $menu = $app->menu;
        //添加普通菜单
        $buttons = [
            [
                "type" => "click",
                "name" => "热卖商品",
                "key"  => "V1001_Hot_Goods"
            ],
            [
                "name"       => "菜单",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "用户信息",
                        "url"  => Url::to(['wechat/user'],true),
                    ],
                    [
                        "type" => "view",
                        "name" => "我的订单",
                        "url"  => Url::to(['wechat/orders'],true),
                    ],
                    [
                        "type" => "view",
                        "name" => "绑定账号",
                        "url"  => Url::to(['wechat/bind-acount'],true),
                    ],
                    [
                        "type" => "view",
                        "name" => "解除绑定",
                        "url"  => Url::to(['wechat/unbound'],true),
                    ],
                    [
                        "type" => "click",
                        "name" => "帮助",
                        "key" => "V1001_HELP",
                    ],
                ],
            ],
        ];
        $rs =$menu->add($buttons);

        var_dump($rs);

    }
    public function actionEvent($message){
        switch ($message->Event) {
            case 'subscribe':
                # code...
                break;
            default:
                # code...
                break;
        }

    }

    //个人信息
    public function actionUser(){
        //保存当前路由
        \Yii::$app->session->set('back','wechat/user');
        //获取个人信息
        $model= \Yii::$app->user->identity;
        //获取个人信息
        return $this->render('userInfo',['model'=>$model]);

    }
    //查询个人订单
    public function actionOrders(){
        //如果当前用户已经绑定账户
        //获取当前账户的订单
        $orders = Order::find()->where(['member_id'=>\Yii::$app->user->id])->all();
        //显示订单列表
        return $this->render('orderList',['models'=>$orders]);
    }
    public function actionBindAcount(){
        //获取openid
        $openid = \Yii::$app->session->get('openid');
        //判断用户是否登陆
        if(\Yii::$app->user->isGuest){
                //如果用户没有登录判断是否绑定帐号,若绑定了则实习自动登录
                    $member = Member::findOne(['openid'=>$openid]);
                        //自动登录实现（用户绑定了账号，但是没有登录则自动登录）
                    if($member!=null && \Yii::$app->user->login($member)){
                            //自动登录成功后刷新页面
                            return $this->refresh();
                    }
                //如果用户没有登录且没有绑定账户则显示登录页面
                //实例化表单模型
                    $model = new BindForm();
                    //加载数据，和验证数据
                    if($model->load(\Yii::$app->request->post()) && $model->validate()){
                            //把用户账号与openid绑定
                        $model->openid = $openid;
                            //登录
                        if($model->login()){
                            // 登录成功 添加提示信息
                            \Yii::$app->session->set('success','绑定账户成功'.\Yii::$app->session->get('back'));
                            //如果有回跳参数，则跳转到之前的页面
                            $this->actionJump();
                            return $this->refresh();//登录成功后涮新页面
                        }
                        //登录失败
                        \Yii::$app->session->set('error','绑定账户失败，用户名或密码错误');
                    }
                    //var_dump($model);
                    //显示登录页面的视图
                    return $this->render('bind',['model'=>$model]);
        }elseif(\Yii::$app->session->has('back')){
            //得到用户的openid后跳转会之前的页面
            $back = \Yii::$app->session->get('back');
            \Yii::$app->session->remove('back');
            return $this->redirect([$back]);
        }
        //如果用户已经登录则显示解除绑定页面
        return $this->render('unbound');

    }

    public  function actionGetOpenid(){
        //检查session中是否有openid
        //如果没有
        if(!\Yii::$app->session->has('openid')){
            //获取用户的openid
            //ehco ‘user';
            $app = new Application(\Yii::$app->params['wechat']);
            $response = $app->oauth->redirect();
            //将当前路由保存到session，便于授权回掉地址跳转到当前页面
            \Yii::$app->session->set('toGetOpenId','wechat/get-openid');
            $response->send();
        }

        $this->actionJump();

        return $this->redirect(['wechat/bind-acount']);
    }

    /**
     * 解除绑定 同时注销当前登录的用户
     * @param null $openid
     * @return string
     */
    public function actionUnbound($openid = null){
        //解除绑定，把当前登录用户的openid更新为0
        if($openid !=null){
            $rs = Member::find()->where(['openid'=>$openid])->one()->updateAttributes(['openid'=>0]);
        }else{
            //得到当前登录用户id，然后更新openid
            $userid = \Yii::$app->user->id;
            $rs = Member::find()->where(['id'=>$userid])->one()->updateAttributes(['openid'=>0]);
        }
        //注销账户
        $result = \Yii::$app->user->logout();
        //注销成功后，关闭当前页面
        if($result){
            \Yii::$app->session->set('success','解除绑定成功'.\Yii::$app->session->get('back'));
        }
        $this->actionJump();
        return '解除绑定成功';

    }

    //网页授权回掉地址 引导用户给予授权

    /**
    （A）用户打开客户端以后，客户端要求用户给予授权。
    （B）用户同意给予客户端授权。
    （C）客户端使用上一步获得的授权，向认证服务器申请令牌。
    （D）认证服务器对客户端进行认证以后，确认无误，同意发放令牌。
    （E）客户端使用令牌，向资源服务器申请获取资源。
    （F）资源服务器确认令牌无误，同意向客户端开放资源。
     * @return string |
     */
    public function actionCallback(){
        $app = new Application(\Yii::$app->params['wechat']);
        /** @var  $user User*/
        $user = $app->oauth->user();
        //获取用户的openid
        $id = $user->getId();
        //将用户的openid保存到session
        \Yii::$app->session->set('openid',$id);
        //跳回请求的地址
        $this->actionJump();
        return $this->redirect(['wechat/bind-acount']);
    }

    public function actionHotGoods(){
        $Agoods = Goods::find()->where(['&','status',2])->limit(5)->all();
        $results = [];
        /** @var  $goods \backend\models\Goods*/
        foreach($Agoods as $goods){
            //
            $news = new News([
                'title'       => $goods->name,
                'description' => $goods->name,
                'url'         => $goods->logoUrl(),
                'image'       => $goods->logoUrl(),
            ]);
            $results[] = $news;
        }

        return $results;

    }

    public function actionJump(){
        if(\Yii::$app->session->has('back')){
            //得到用户的openid后跳转会之前的页面
            $back = \Yii::$app->session->get('back');
            //\Yii::$app->session->remove('back');
            return $this->redirect([$back]);
        }elseif(\Yii::$app->session->has('toGetOpenId')){
            //跳转到获取openid的方法
            $toopenid =  \Yii::$app->session->get('toGetOpenId');
            \Yii::$app->session->remove('toGetOpenId');
            return $this->redirect([$toopenid]);
        }

        return $this->redirect(['wechat/bind-acount']);
    }

    public function actionTest(){
        $f = function ($d){
          var_dump($this);
        };
        //$this;
        $f(12);
    }


}